﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PictureManager.Core;
using WeifenLuo.WinFormsUI.Docking;
using PictureManager.Controls;
using Infrastructure.UI;
using System.Diagnostics;
using Infrastructure.Library;

namespace PictureManager
{
    public partial class frmMaintenance : BaseForm
    {
        #region Fields
        private PictureItem currentItem;
        private String RootNode;
        private DataTable dtPicture;
        public DataTable DtPicture
        {
            get
            {
                if (dtPicture == null)
                {
                    dtPicture = new DataTable();
                    dtPicture.Columns.Add("FileName", typeof(String));
                    dtPicture.Columns.Add("Path", typeof(String));
                    dtPicture.Columns.Add("Image", typeof(Image));
                }
                return dtPicture;
            }
            set
            {
                dtPicture = value;
            }
        }

        #endregion

        public frmMaintenance()
        {
            InitializeComponent();
        }

        #region Methods

        #region Override Methods

        public override void InitData()
        {
            base.InitData();
            RootNode = PictureSettings.Instance.PictureRootNode;
            BindingTreeView(RootNode, treeViewPicture.Nodes);
            this.colFileName.HeaderCell.SortGlyphDirection = SortOrder.Ascending;
        }

        public override void InitEvent()
        {
            base.InitEvent();

            this.toolBarAdmin.ItemClicked += new ToolStripItemClickedEventHandler(toolBarAdmin_ItemClicked);

            this.treeViewPicture.AfterSelect += new TreeViewEventHandler(treeViewPicture_AfterSelect);
            this.treeViewPicture.MouseClick += new MouseEventHandler(treeViewPicture_MouseClick);
            this.treeViewPicture.DragOver += new DragEventHandler(treeViewPicture_DragOver);
            this.treeViewPicture.DragDrop += new DragEventHandler(treeViewPicture_DragDrop);
            this.treeViewPicture.ItemDrag += new ItemDragEventHandler(treeViewPicture_ItemDrag);

            this.contextMenuTreeView.ItemClicked += new ToolStripItemClickedEventHandler(contextMenuTreeView_ItemClicked);
            this.contextMenuTreeView.Opening += new CancelEventHandler(contextMenuTreeView_Opening);
            this.contextMenuGridView.ItemClicked += new ToolStripItemClickedEventHandler(contextMenuGridView_ItemClicked);
            this.contextMenuGridView.Opening += new CancelEventHandler(contextMenuGridView_Opening);

            this.grvPictures.RowPostPaint += new DataGridViewRowPostPaintEventHandler(grvPictures_RowPostPaint);
            this.grvPictures.UserDeletingRow += new DataGridViewRowCancelEventHandler(grvPictures_UserDeletingRow);
            this.grvPictures.UserDeletedRow += new DataGridViewRowEventHandler(grvPictures_UserDeletedRow);
            this.grvPictures.DragDrop += new DragEventHandler(grvPictures_DragDrop);
            this.grvPictures.DragOver += new DragEventHandler(grvPictures_DragOver);
            this.grvPictures.DoubleClick += new EventHandler(grvPictures_DoubleClick);
            this.chkShowPathColumn.CheckedChanged += new EventHandler(chkShowPathColumn_CheckedChanged);
            this.timerprogress.Tick += new EventHandler(timerprogress_Tick);
            PictureItem.Saved += new EventHandler<SaveEventArgs>(PictureItem_Saved);
        }

        void grvPictures_DoubleClick(object sender, EventArgs e)
        {
            if (this.grvPictures.SelectedRows.Count >= 0 && this.grvPictures.SelectedRows[0].Cells["colPath"] != null)
            {
                Process pro = new Process();
                pro.StartInfo = new ProcessStartInfo(this.grvPictures.SelectedRows[0].Cells["colPath"].Value.ToString());
                pro.Start();
            }
        }

        #endregion

        private void BindingTreeView(string parentID, TreeNodeCollection nodeCollection)
        {
            PictureItem.PictureList.Where(p => p.ParentID == parentID).ToList().ForEach(p =>
            {
                TreeNode node = new TreeNode();
                node.Name = p.ID;
                node.Text = p.Name;
                node.Tag = p;
                nodeCollection.Add(node);
                BindingTreeView(p.ID, node.Nodes);

            });
        }

        private void BindingControl()
        {
            BindingControl(currentItem);
        }

        private void BindingControl(PictureItem currentItem)
        {
            if (currentItem == null)
            {
                ClearData();
                return;
            }
            BindingManager.Instance.Binding(pnlInfo, currentItem, true);
            DtPicture.Rows.Clear();
            pnlShow.Controls.Clear();
            (from t in currentItem.FileNames
             select new
             {
                 FileName = t.Value,
                 Path = t.Key
             }).ToList().ForEach(k =>
             {
                 DataRow dr = DtPicture.NewRow();
                 dr["FileName"] = k.FileName;
                 dr["Path"] = k.Path;
                 try
                 {
                     PictureBox pic = new PictureBox();

                     System.Drawing.Image img = System.IO.File.Exists(k.Path) ? Image.FromFile(k.Path) : new Bitmap(100, 100);
                     System.Drawing.Image bmp = new System.Drawing.Bitmap(img);
                     img.Dispose();
                     pic.Width = bmp.Width;
                     pic.Height = bmp.Height;
                     pic.Image = GraphicsImage(bmp);
                     
                     dr["Image"] = pic.Image;
                     pnlShow.Controls.Add(pic);
                 }
                 catch
                 {
                     dr["Image"] = null;
                 }
                 DtPicture.Rows.Add(dr);

             });
            DtPicture.AcceptChanges();
            grvPictures.DataSource = DtPicture;
            this.grpPictures.Text = PictureManager.Properties.Resources.Pictures + "(" + DtPicture.Rows.Count + ")";
        }

        private Image GraphicsImage(Image image)
        {
            while (image.Height > 200 && image.Width > 200)
                image = GraphicsControl.Instance.ReSizeImage(image, new Size(image.Width / 2 == 0 ? image.Width : image.Width / 2, image.Height / 2 == 0 ? image.Height : image.Height / 2));
            return image;
        }

        private void ClearData()
        {
            this.txtName.Text = String.Empty;
            this.txtPath.Text = String.Empty;
            this.txtDesc.Text = String.Empty;
            this.chkIsNameBeFileName.Checked = false;
            DtPicture.Rows.Clear();
            this.grvPictures.DataSource = DtPicture;
            this.grpPictures.Text = PictureManager.Properties.Resources.Pictures;
        }

        private void EndCurrentEdit()
        {
            if (currentItem != null)
            {
                this.grvPictures.EndEdit();
                this.BindingContext[this.grvPictures.DataSource].EndCurrentEdit();
                if (!currentItem.IsChanged && DtPicture.GetChanges() == null) return;
                if (DtPicture.GetChanges() != null)
                {
                    foreach (DataRow dr in DtPicture.GetChanges().Rows)
                    {
                        if (dr.RowState == DataRowState.Deleted || dr.RowState == DataRowState.Detached)
                        {
                            currentItem.FileNames.Remove(dr["Path", DataRowVersion.Original].ToString());
                            currentItem.MarkChanged();
                            continue;
                        }
                        currentItem.FileNames[dr["Path"].ToString()] = dr["FileName"].ToString();
                    }
                }
                currentItem.SetRelativePathEmpty();
            }
        }

        private void SaveCurrentItem()
        {
            if (currentItem != null)
            {
                EndCurrentEdit();
                currentItem.Save();
            }
        }

        private void SetMeuItemVisible(Boolean isVisible)
        {
            this.meuDelete.Visible = isVisible;
            this.meuAsRootNode.Visible = isVisible;
            this.meuMoveToFolderTree.Visible = isVisible;
        }

        private void RefreshTreeView()
        {
            treeViewPicture.Nodes.Clear();
            BindingTreeView(RootNode, treeViewPicture.Nodes);
            if (currentItem != null && treeViewPicture.Nodes.Find(currentItem.ID, true).Count() > 0)
                treeViewPicture.SelectedNode = treeViewPicture.Nodes.Find(currentItem.ID, true)[0];
            else if (currentItem != null && treeViewPicture.Nodes.Find(currentItem.ParentID, true).Count() > 0)
                treeViewPicture.SelectedNode = treeViewPicture.Nodes.Find(currentItem.ParentID, true)[0];
            else if (treeViewPicture.Nodes.Find(PictureSettings.Instance.PictureRootNode, true).Count() > 0)
                treeViewPicture.SelectedNode = treeViewPicture.Nodes.Find(PictureSettings.Instance.PictureRootNode, true)[0];
            BindingControl();
        }

        private List<System.Windows.Forms.ToolStripItem> GetFoldersWithRoot()
        {
            List<System.Windows.Forms.ToolStripItem> toolStripItems = new List<ToolStripItem>();
            ToolStripMenuItem RootItem = new ToolStripMenuItem();
            RootItem.Name = "meu" + PictureSettings.Instance.PictureRootNode;
            RootItem.Text = PictureSettings.Instance.PictureRootNode;
            RootItem.Tag = PictureItem.RootItem;
            toolStripItems.Add(RootItem);
            toolStripItems.AddRange(GetFolders());
            return toolStripItems;
        }

        private List<System.Windows.Forms.ToolStripItem> GetFolders()
        {
            List<System.Windows.Forms.ToolStripItem> toolStripItems = new List<ToolStripItem>();
            PictureItem.PictureList.ForEach(p =>
            {
                ToolStripMenuItem item = new ToolStripMenuItem();
                item.Name = "meu" + p.ID;
                item.Text = p.RelativePath;
                item.Tag = p;
                toolStripItems.Add(item);
            });
            return toolStripItems;
        }

        private void BackgroundWorker(Boolean isBackgroundWork)
        {
            this.grpDetail.Enabled = !isBackgroundWork;
            this.pnlTreeView.Enabled = !isBackgroundWork;
            this.progressBar.Visible = isBackgroundWork;
            this.timerprogress.Enabled = isBackgroundWork;
        }

        private void LoadDirectory()
        {
            folderBrowserDialog.SelectedPath = AppDomain.CurrentDomain.BaseDirectory;
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                LoadDirectory(folderBrowserDialog.SelectedPath);
            }
        }

        private void LoadDirectory(String Path)
        {
            BackgroundWorker(true);

            Func<String, Boolean> syncOper = new Func<String, bool>(LoadDirectorySync);
            syncOper.BeginInvoke(Path,
                delegate(IAsyncResult ar)
                {
                    this.Invoke(
                        (Action)delegate
                        {
                            if (!syncOper.EndInvoke(ar))
                            {

                                MessageBox.Show(PictureManager.Properties.Resources.FailtoLoad,
                                    PictureManager.Properties.Resources.Error,
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            else
                            {
                                PictureItem.SaveAll();
                                RefreshTreeView();
                                MessageBox.Show(PictureManager.Properties.Resources.LoadSuccessfully,
                                    PictureManager.Properties.Resources.Information,
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            BackgroundWorker(false);
                        }
                    );
                }
            , null);
        }

        private bool LoadAllDirectory(String[] Paths)
        {
            bool isLoadSuccessful = true;
            for (int i = 0; i <= Paths.Length - 1; i++)
            {
                if (!System.IO.Directory.Exists(Paths[i])) continue;
                isLoadSuccessful = isLoadSuccessful && PictureManager.Core.Util.LoadDirectory(Paths[i], PictureSettings.Instance.PictureRootNode);
            }
            return isLoadSuccessful;
        }

        private bool LoadDirectorySync(String directory)
        {
            return PictureManager.Core.Util.LoadDirectory(directory, PictureSettings.Instance.PictureRootNode);
        }

        private void SyncDirectory()
        {
            BindingManager.Instance.ClearBinding();
            BackgroundWorker(true);
            Func<List<PictureItem>, bool> syncOper = new Func<List<PictureItem>, bool>(PictureManager.Core.Util.SyncPictureDataToFolder);
            syncOper.BeginInvoke(PictureItem.PictureList,
               delegate(IAsyncResult ar)
                {
                    this.Invoke(
                        (Action)delegate
                        {
                            if (!syncOper.EndInvoke(ar))
                            {
                                MessageBox.Show(PictureManager.Properties.Resources.FailtoSync, PictureManager.Properties.Resources.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            else
                            {
                                PictureItem.SaveAll();
                                RefreshTreeView();
                                MessageBox.Show(PictureManager.Properties.Resources.SyncSuccessfully, PictureManager.Properties.Resources.Information, MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            BackgroundWorker(false);
                        }
                    );
                }, null);
        }

        private void DeleteTreeNode()
        {
            if (this.treeViewPicture.SelectedNode == null) return;
            PictureItem item = this.treeViewPicture.SelectedNode.Tag as PictureItem;
            if (item == null) return;
            List<PictureItem> deleteItems = new List<PictureItem>();
            deleteItems.Add(item);
            PictureManager.Core.Util.GetChildPictureItems(deleteItems, item.ID);
            deleteItems.ForEach(d => PictureItem.PictureList.Remove(PictureItem.GetItem(d.ID)));
            this.treeViewPicture.Nodes.Remove(this.treeViewPicture.SelectedNode);
            if (this.treeViewPicture.Nodes.Count == 0)
            {
                currentItem.Delete();
                currentItem = null;
                BindingControl();
            }
            PictureItem.SaveAll();
            if (item.Path.IndexOf(PictureSettings.Instance.BackupFolder.Replace(@"/", @"\")) > -1) return;
            UtilLib.IOUtil.MovePathToPath(item.Path, System.IO.Path.Combine(PictureSettings.Instance.BackupFolder, item.RelativePath), true);
        }

        private void AddTreeNode()
        {
            PictureItem newItem = new PictureItem();
            newItem.ID = Guid.NewGuid().ToString();
            newItem.Name = PictureManager.Properties.Resources.NewFolder;
            if (this.treeViewPicture.SelectedNode == null)
            {
                newItem.ParentID = PictureSettings.Instance.PictureRootNode;
            }
            else
            {
                PictureItem item = this.treeViewPicture.SelectedNode.Tag as PictureItem;
                if (item == null)
                {
                    newItem.ParentID = PictureSettings.Instance.PictureRootNode;
                }
                else
                    newItem.ParentID = item.ID;
            }
            newItem.Save();
            TreeNode[] nodes = this.treeViewPicture.Nodes.Find(newItem.ID, true);
            if (nodes == null || nodes.Count() == 0)
                return;
            this.treeViewPicture.SelectedNode = nodes[0];
        }

        private void DeleteFileItem()
        {
            foreach (DataGridViewRow dr in this.grvPictures.SelectedRows)
            {
                if (dr.Cells["colPath"].Value == null) continue;
                currentItem.FileNames.Remove(dr.Cells["colPath"].Value.ToString());
                UtilLib.IOUtil.MoveFileToPath(dr.Cells["colPath"].Value.ToString(), System.IO.Path.Combine(PictureSettings.Instance.BackupFolder, currentItem.RelativePath), false);
            }
            currentItem.MarkChanged();
            currentItem.Save();
            BindingControl();
        }

        private void LoadPictures()
        {
            openFileDialogPictureGrid.InitialDirectory = currentItem.Path;
            if (openFileDialogPictureGrid.ShowDialog() == DialogResult.OK)
            {
                openFileDialogPictureGrid.FileNames.ToList().ForEach(f =>
                {
                    if (f != null && !currentItem.FileNames.ContainsKey(f))
                        currentItem.FileNames.Add(f, System.IO.Path.GetFileNameWithoutExtension(f));
                });
                currentItem.MarkChanged();
                currentItem.Save();
                BindingControl();
            }
        }
        #endregion

        #region Events

        void toolBarAdmin_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem == this.btnLoad)
            {
                LoadDirectory();
            }
            else if (e.ClickedItem == this.btnSaveAll)
            {
                PictureItem.SaveAll();
            }
            else if (e.ClickedItem == this.btnSync)
            {
                SaveCurrentItem();
                SyncDirectory();
            }
        }

        void treeViewPicture_AfterSelect(object sender, TreeViewEventArgs e)
        {
            SaveCurrentItem();
            PictureItem item = e.Node.Tag as PictureItem;
            if (item == null)
                currentItem = null;
            else
                currentItem = PictureItem.GetItem(item.ID);
            BindingControl();
            e.Node.Expand();
        }

        void treeViewPicture_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                this.treeViewPicture.SelectedNode = this.treeViewPicture.GetNodeAt(e.X, e.Y);
            }
        }

        void treeViewPicture_DragOver(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop) || e.Data.GetDataPresent("System.Windows.Forms.TreeNode", false))
            {
                e.Effect = DragDropEffects.Move;
            }
        }

        void treeViewPicture_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                #region FileDrop
                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
                if (files.All(f => !System.IO.Directory.Exists(f))) return;
                BackgroundWorker(true);
                Func<String[], bool> syncAllOper = new Func<string[], bool>(LoadAllDirectory);
                syncAllOper.BeginInvoke(files,
                    new AsyncCallback(delegate(IAsyncResult ar)
                        {
                            this.Invoke(
                            (MethodInvoker)delegate
                            {
                                if (!syncAllOper.EndInvoke(ar))
                                {
                                    MessageBox.Show(PictureManager.Properties.Resources.FailtoLoadAll, PictureManager.Properties.Resources.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                                else
                                {
                                    PictureItem.SaveAll();
                                    RefreshTreeView();
                                    MessageBox.Show(PictureManager.Properties.Resources.LoadAllSuccessfully, PictureManager.Properties.Resources.Information, MessageBoxButtons.OK, MessageBoxIcon.Information);
                                }
                                BackgroundWorker(false);
                            }
                        );
                        }), null);
                #endregion
            }
            else if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode", false))
            {
                Point point = ((TreeView)sender).PointToClient(new Point(e.X, e.Y));
                TreeNode targetTreeNode = ((TreeView)sender).GetNodeAt(point);
                TreeNode treeNode = (TreeNode)e.Data.GetData("System.Windows.Forms.TreeNode");

                if (treeNode == null) return;
                PictureItem dragItem = treeNode.Tag as PictureItem;
                if (targetTreeNode == null && dragItem != null && dragItem.ParentID != PictureSettings.Instance.PictureRootNode)
                {
                    dragItem.ParentID = PictureSettings.Instance.PictureRootNode;
                }
                else
                {
                    PictureItem desItem = targetTreeNode.Tag as PictureItem;
                    if (desItem == null || dragItem == null || dragItem.ParentID == desItem.ID)
                        return;
                    dragItem.ParentID = desItem.ID;
                }
                dragItem.SetRelativePathEmpty();
                PictureItem.SaveAll();
                RefreshTreeView();
            }
        }

        void treeViewPicture_ItemDrag(object sender, ItemDragEventArgs e)
        {
            this.DoDragDrop(e.Item, DragDropEffects.Move);
        }

        void contextMenuTreeView_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem == this.meuLoadFolder)
            {
                LoadDirectory();
            }
            else if (e.ClickedItem == this.meuDelete)
            {
                DeleteTreeNode();
            }
            else if (e.ClickedItem == this.meuNewFolder)
            {
                AddTreeNode();
            }
            else if (e.ClickedItem == this.meuAsRootNode)
            {
                if (this.treeViewPicture.SelectedNode == null) return;
                PictureItem item = this.treeViewPicture.SelectedNode.Tag as PictureItem;
                if (item == null) return;
                RootNode = item.ParentID;
                RefreshTreeView();
            }
            else if (e.ClickedItem == this.meuResetRootNode)
            {
                RootNode = PictureSettings.Instance.PictureRootNode;
                RefreshTreeView();
            }

        }

        void contextMenuTreeView_Opening(object sender, CancelEventArgs e)
        {
            this.meuMoveToFolderTree.DropDownItems.Clear();
            SetMeuItemVisible(false);
            if (this.treeViewPicture.SelectedNode == null)
            {
                return;
            }
            SetMeuItemVisible(true);
            PictureItem item = this.treeViewPicture.SelectedNode.Tag as PictureItem;
            if (item == null) return;
            //Not child folder items,Not first Parent folder,Not self folder
            this.meuMoveToFolderTree.DropDownItems.AddRange(GetFoldersWithRoot().Where(p =>
            {
                PictureItem meuItem = p.Tag as PictureItem;
                if (meuItem == null) return false;
                if (meuItem.ID == item.ID || meuItem.IsParentID(item.ID) || item.ParentID == meuItem.ID)
                    return false;
                p.Click += new EventHandler(TreeView_MenuItem_Click);
                return true;
            }).ToArray());
            if (this.meuMoveToFolderTree.DropDownItems.Count == 0)
                this.meuMoveToFolderTree.Visible = false;
        }

        void TreeView_MenuItem_Click(object sender, EventArgs e)
        {
            if (this.treeViewPicture.SelectedNode == null) return;
            ToolStripMenuItem toolItem = sender as ToolStripMenuItem;
            PictureItem desItem = toolItem.Tag as PictureItem;
            PictureItem selectItem = this.treeViewPicture.SelectedNode.Tag as PictureItem;
            if (desItem == null || selectItem == null)
                return;
            selectItem.ParentID = desItem.ID;
            selectItem.SetRelativePathEmpty();
            PictureItem.SaveAll();
            RefreshTreeView();
        }

        void contextMenuGridView_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem == this.meuLoadPictures)
            {
                LoadPictures();
            }
            else if (e.ClickedItem == this.meuDeleteFileItem)
            {
                DeleteFileItem();
            }
        }

        void contextMenuGridView_Opening(object sender, CancelEventArgs e)
        {
            this.meuMoveToFolderGrid.DropDownItems.Clear();
            if (currentItem == null)
            {
                e.Cancel = true;
                return;
            }
            if (currentItem.FileNames.Count == 0 || this.grvPictures.SelectedRows.Count == 0)
            {
                this.meuMoveToFolderGrid.Visible = false;
                return;
            }
            this.meuMoveToFolderGrid.Visible = true;
            //add not child folder items
            this.meuMoveToFolderGrid.DropDownItems.AddRange(GetFolders().Where(p =>
            {
                PictureItem meuItem = p.Tag as PictureItem;
                if (meuItem == null) return false;
                if (meuItem.ID == currentItem.ID || meuItem.ID == PictureSettings.Instance.PictureRootNode)
                    return false;
                p.Click += new EventHandler(GridView_MenuItem_Click);
                return true;
            }).ToArray());
            if (this.meuMoveToFolderGrid.DropDownItems.Count == 0)
                this.meuMoveToFolderGrid.Visible = false;
        }

        void GridView_MenuItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem toolItem = sender as ToolStripMenuItem;
            PictureItem desItem = toolItem.Tag as PictureItem;
            if (desItem == null) return;
            foreach (DataGridViewRow dr in this.grvPictures.SelectedRows)
            {
                if (dr.Cells["colPath"].Value == null) continue;
                currentItem.FileNames.Remove(dr.Cells["colPath"].Value.ToString());
                if (!desItem.FileNames.ContainsKey(dr.Cells["colPath"].Value.ToString()))
                    desItem.FileNames.Add(dr.Cells["colPath"].Value.ToString(), dr.Cells["colFileName"].Value.ToString());
            }
            PictureItem.SaveAll();
            RefreshTreeView();
        }

        void grvPictures_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, grvPictures.RowHeadersWidth - 4, e.RowBounds.Height);

            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), grvPictures.RowHeadersDefaultCellStyle.Font, rectangle,
                grvPictures.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }

        void grvPictures_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            DialogResult response = MessageBox.Show(PictureManager.Properties.Resources.DeleteRowConfirm, PictureManager.Properties.Resources.Confirm, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (response == DialogResult.No)
                e.Cancel = true;
        }

        void grvPictures_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
        {
            SaveCurrentItem();
        }

        void grvPictures_DragOver(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Move;
            }
        }

        void grvPictures_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] file = (string[])e.Data.GetData(DataFormats.FileDrop);
                for (int i = 0; i <= file.Length - 1; i++)
                {
                    if (!PictureManager.Core.Util.PicExtension.Contains(System.IO.Path.GetExtension(file[0]))) continue;
                    DataRow dr = DtPicture.NewRow();
                    dr["FileName"] = System.IO.Path.GetFileNameWithoutExtension(file[i]);
                    dr["Path"] = file[i];
                    try
                    {
                        PictureBox pic = new PictureBox();
                        System.Drawing.Image img = System.IO.File.Exists(file[i]) ? Image.FromFile(file[i]) : new Bitmap(10, 10);
                        System.Drawing.Image bmp = new System.Drawing.Bitmap(img);
                        img.Dispose();
                        pic.Image = GraphicsImage(bmp);
                        dr["Image"] = pic.Image;
                    }
                    catch
                    {
                        dr["Image"] = null;
                    }
                    DtPicture.Rows.Add(dr);
                }
                SaveCurrentItem();
            }
        }

        void timerprogress_Tick(object sender, EventArgs e)
        {
            if (this.progressBar.Value < this.progressBar.Maximum)
            {
                this.progressBar.Value += 1;
            }
            else
                this.progressBar.Value = 0;
        }

        void PictureItem_Saved(object sender, SaveEventArgs e)
        {
            if (e.Action == SaveAction.Update)
            {
                PictureItem item = sender as PictureItem;
                if (item == null) return;
                TreeNode[] nodes = this.treeViewPicture.Nodes.Find(item.ID, true);
                if (nodes == null || nodes.Count() == 0) return;
                TreeNode node = nodes[0];
                node.Name = item.ID;
                node.Text = item.Name;
                node.Tag = item;
            }
            else if (e.Action == SaveAction.Insert)
            {
                PictureItem item = sender as PictureItem;
                if (item == null) return;
                TreeNode[] nodes = this.treeViewPicture.Nodes.Find(item.ParentID, true);
                if (nodes == null || nodes.Count() == 0)
                {
                    if (item.ParentID == PictureSettings.Instance.PictureRootNode)
                    {
                        TreeNode node = new TreeNode();
                        node.Name = item.ID;
                        node.Text = item.Name;
                        node.Tag = item;
                        this.treeViewPicture.Nodes.Add(node);
                        this.treeViewPicture.SelectedNode = node;
                    }
                    return;
                }
                else
                {
                    TreeNode node = new TreeNode();
                    node.Name = item.ID;
                    node.Text = item.Name;
                    node.Tag = item;
                    nodes[0].Nodes.Add(node);
                    this.treeViewPicture.SelectedNode = node;
                }
            }
            else if (e.Action == SaveAction.Delete)
            {
                PictureItem item = sender as PictureItem;
                if (item == null || currentItem == null || item.ID != currentItem.ID) return;
                TreeNode[] nodes = this.treeViewPicture.Nodes.Find(item.ID, true);
                if (nodes == null || nodes.Count() == 0)
                    return;
                if (item.ParentID == PictureSettings.Instance.PictureRootNode)
                {
                    this.treeViewPicture.Nodes.Remove(nodes[0]);
                    return;
                }
                TreeNode[] parentnodes = this.treeViewPicture.Nodes.Find(item.ParentID, true);
                if (parentnodes == null || parentnodes.Count() == 0)
                    return;
                parentnodes[0].Nodes.Remove(nodes[0]);
            }
        }

        void chkShowPathColumn_CheckedChanged(object sender, EventArgs e)
        {
            this.grvPictures.Columns[colPath.Name].Visible = this.chkShowPathColumn.Checked;
        }

        #endregion

    }
}
